//
//  Album.m
//  UI_15_下午练习_collectionView封装轮播图
//
//  Created by li cheng on 16/8/4.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "Album.h"
//#import "ImageViewCollectionViewCell.h"
#define kUIScreenBounds [UIScreen mainScreen].bounds
@interface Album()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *albumCollectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSArray *sourceArray;
@property (nonatomic, strong) NSMutableArray *imageNames;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *label;
@end
@implementation Album
- (instancetype)initWithFrame:(CGRect)frame array:(NSArray *)array{
    self = [super initWithFrame:frame];
    if (self) {
        _sourceArray = array;
        [self createCollection];
        [self createpageControl];
        [self createLabel];
        [self handleImage];
        [self addTimer];
    }
    return self;
}
#pragma mark - 照片处理,前后加一张图片
- (void)handleImage{
    _imageNames = [NSMutableArray array];
    [_imageNames addObject:[_sourceArray lastObject]];
    for (NSString *imageName in _sourceArray) {
        [_imageNames addObject:imageName];
    }
    [_imageNames addObject:[_sourceArray firstObject]];
}

#pragma mark - 创建pageControl
- (void)createpageControl{
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.bounds) / 4, CGRectGetHeight(self.bounds) - 100, CGRectGetWidth(self.bounds) / 2, 40)];
    [self addSubview:_pageControl];
    _pageControl.backgroundColor = [UIColor redColor];
    _pageControl.numberOfPages = _sourceArray.count;
    [_pageControl addTarget:self action:@selector(handlepage:) forControlEvents:UIControlEventValueChanged];
}
#pragma mark - 创建CollectionView
- (void)createCollection{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds));
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    _albumCollectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    _albumCollectionView.contentOffset = CGPointMake(kUIScreenBounds.size.width, 0);
    _albumCollectionView.pagingEnabled = YES;
    [self addSubview:_albumCollectionView];
    _albumCollectionView.delegate = self;
    _albumCollectionView.dataSource = self;
    [_albumCollectionView registerClass:[ImageViewCollectionViewCell class] forCellWithReuseIdentifier:@"ImageViewCollectionViewCell"];
}
#pragma mark - 创建定时器
- (void)addTimer{
    
    // 仅仅是创建,并没有加入runloop中
    // timer方法得加上runloop才能动
        self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // modes代表了多种的状态,就是默认状态和滚动状态,当放下tableView上面的时候,上面的定时器也能走
    // NSRunLoopCommonModes 和 NSDefaultRunLoopMode
    // 后者代表默认的状态,scheduledTimerWithTimeInterval是默认的
    // 前者是默认状态和滑动状态
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    
    
    //    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    
    
    
    
//    (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
//    self.timer = [NSTimer timerWithTimeInterval: invocation:<#(nonnull NSInvocation *)#> repeats:<#(BOOL)#>]
//    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
//    
//    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
//    self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
//    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}
- (void)nextImage{
    int page = (int)_pageControl.currentPage;
    if (page == _imageNames.count - 2){
        page = 0;
    }
    page++;
    NSLog(@"%d", page);
    NSLog(@"----------------%ld", _pageControl.currentPage);
    CGFloat x = page * kUIScreenBounds.size.width + kUIScreenBounds.size.width;
    _albumCollectionView.contentOffset = CGPointMake(x, 0);
}
#pragma mark - collectionView 代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imageNames.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ImageViewCollectionViewCell *cell = [collectionView    dequeueReusableCellWithReuseIdentifier:@"ImageViewCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random()% 256 / 255.0f green:arc4random()% 256 / 255.0f blue:arc4random()% 256 / 255.0f alpha:1];
    cell.imageView.image = [UIImage imageNamed:_imageNames[indexPath.row]];
    if (self.delegateTwo && [self.delegateTwo respondsToSelector:@selector(collectionView:cellForItemAtIndexPath:cell:)]) {
        [self.delegateTwo collectionView:collectionView cellForItemAtIndexPath:indexPath cell:cell];
    }
    return cell;
}
#pragma mark - 滑动的时候实现的方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x < kUIScreenBounds.size.width) {
        [_albumCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_imageNames.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if(scrollView.contentOffset.x > (_imageNames.count - 2) * [UIScreen mainScreen].bounds.size.width) {
        [_albumCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    _pageControl.currentPage = scrollView.contentOffset.x / kUIScreenBounds.size.width - 1;
    NSString *string = [NSString stringWithFormat:@"这是第%ld张图片", _pageControl.currentPage];
    _label.text = string;
    
}
#pragma mark - 滑动完成时的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    //计算页码
    CGFloat scrolleViewWidth = scrollView.frame.size.width;
    CGFloat x = scrollView.contentOffset.x;
    int page = x / scrolleViewWidth - 1;
    if (page == _sourceArray.count) {
        page = 0;
    }
//    if (page == 0) {
//        page = (int)_sourceArray.count;
//    }
    _pageControl.currentPage = page;
//    [_pageControl sizeForNumberOfPages:page];
}

#pragma mark - page点击方法
- (void)handlepage:(UIPageControl *)page{
    [self.albumCollectionView setContentOffset:CGPointMake(CGRectGetWidth(kUIScreenBounds) * (_pageControl.currentPage + 1), 0) animated:YES];
}
#pragma mark - 移除定时器
- (void)removeTimer
{
    [_timer invalidate];
    _timer = nil;
}
//开始拖拽视图
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
{
    //开始手动拖拽的时候移除定时器
    [self removeTimer];
}
//完成拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
{
    //手动拖拽的时候添加定时器
        [self addTimer];
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.delegate && [self.delegate respondsToSelector:@selector(collectionView:indexPath:)]) {
        [self.delegate collectionView:collectionView indexPath:indexPath];
    }
}
#pragma mark - 创建label
- (void)createLabel{
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, self.bounds.size.width, 40)];
    //    _pageControl.currentPage
    _label.textAlignment = 1;
    [self addSubview:_label];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


@interface ImageViewCollectionViewCell()
@property (nonatomic, strong) UIImageView *myImageView;
@end
@implementation ImageViewCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _myImageView = [[UIImageView alloc] init];
        [self.contentView addSubview:_myImageView];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    _myImageView.frame = self.contentView.bounds;
}
@end
